package com.tang.service;

import com.tang.dao.ScheduleJobMapper;
import com.tang.factory.QuartzJobFactory;
import com.tang.factory.QuartzJobFactoryDisallowConcurrentExecution;
import com.tang.pojo.ScheduleJob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author 唐一菲
 * @Description: 计划任务管理
 * Quartz任务调度的核心元素为：Scheduler——任务调度器、Trigger——触发器、Job——任务。
 * 其中trigger和job是任务调度的元数据，scheduler是实际执行调度的控制器。
 * Trigger是用于定义调度时间的元素，即按照什么时间规则去执行任务。
 * Quartz中主要提供了四种类型的trigger：SimpleTrigger，CronTirgger，DateIntervalTrigger，和NthIncludedDayTrigger。
 * 这四种trigger可以满足企业应用中的绝大部分需求。
 * Job用于表示被调度的任务。主要有两种类型的job：无状态的（stateless）和有状态的（stateful）。
 * 对于同一个trigger来说，有状态的job不能被并行执行，只有上一次触发的任务被执行完之后，才能触发下一次执行。
 * Job主要有两种属性：volatility和durability，其中volatility表示任务是否被持久化到数据库存储，
 * 而durability表示在没有trigger关联的时候任务是否被保留。
 * 两者都是在值为true的时候任务被持久化或保留。一个job可以被多个trigger关联，
 * 但是一个trigger只能关联一个job。
 * Scheduler由scheduler工厂创建：DirectSchedulerFactory或者StdSchedulerFactory。
 * 第二种工厂StdSchedulerFactory使用较多，因为DirectSchedulerFactory使用起来不够方便，需要作许多详细的手工编码设置。
 * Scheduler主要有三种：RemoteMBeanScheduler，RemoteScheduler和StdScheduler
 * 其他的讲述请参考：https://www.cnblogs.com/zhenyuyaodidiao/p/4755649.html
 */
@Service
@SuppressWarnings({"rawtypes", "unchecked"})
public class JobTaskService {

    private static final Logger log = LogManager.getLogger(JobTaskService.class);

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Resource
    private ScheduleJobMapper scheduleJobMapper;

    /**
     * 从数据库中取 区别于getAllJob
     *
     * @return
     */
    public List<ScheduleJob> getAllTask() {
        return scheduleJobMapper.getAll();
    }

    /**
     * 添加到数据库中 区别于addJob
     */
    public void addTask(ScheduleJob job) {
        job.setCreateTime(new Date());
        scheduleJobMapper.insertSelective(job);
    }

    /**
     * 从数据库中查询job
     */
    public ScheduleJob getTaskById(Long jobId) {
        return scheduleJobMapper.selectByPrimaryKey(jobId);
    }

    /**
     * 更改任务状态
     *
     * @throws SchedulerException
     */
    public void changeStatus(Long jobId, String cmd) throws SchedulerException {
        ScheduleJob job = getTaskById(jobId);
        if (job == null) {
            return;
        }
        if ("stop".equals(cmd)) {
            // 删除任务
            deleteJob(job);
            job.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
        } else if ("start".equals(cmd)) {
            job.setJobStatus(ScheduleJob.STATUS_RUNNING);
            addJob(job);
        }
        scheduleJobMapper.updateByPrimaryKeySelective(job);
    }

    /**
     * 立即运行与暂停作业任务
     *
     * @throws SchedulerException
     */
    public void executePauseJobNow(Long jobId, String cmd)
            throws SchedulerException {
        ScheduleJob job = getTaskById(jobId);
        if (job == null) {
            return;
        }
        if ("stop".equals(cmd)) {
            // 删除任务
            deleteJob(job);
            job.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
        } else if ("start".equals(cmd)) {
//			runAJobNow(job);
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger3", "group1")
                    .startAt(new Date())
                    .withSchedule(
                            SimpleScheduleBuilder.simpleSchedule()
                                    .withIntervalInSeconds(3)
                                    .withRepeatCount(0))//重复执行的次数，因为加入任务的时候马上执行了，所以不需要重复，否则会多一次。  
                    .build();
            Class clazz = ScheduleJob.CONCURRENT_IS.equals(job
                    .getIsConcurrent()) ? QuartzJobFactory.class
                    : QuartzJobFactoryDisallowConcurrentExecution.class;

            JobDetail jobDetail = JobBuilder.newJob(clazz)
                    .withIdentity(job.getJobName(), job.getJobGroup()).build();

            jobDetail.getJobDataMap().put("scheduleJob", job);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
            job.setJobStatus(ScheduleJob.STATUS_RUNNING);
        }
        scheduleJobMapper.updateByPrimaryKeySelective(job);
    }

    /**
     * 更改任务 cron表达式
     *
     * @throws SchedulerException
     */
    public void updateCron(Long jobId, String cron) throws SchedulerException {
        ScheduleJob job = getTaskById(jobId);
        if (job == null) {
            return;
        }
        job.setCronExpression(cron);
        if (ScheduleJob.STATUS_RUNNING.equals(job.getJobStatus())) {
            updateJobCron(job);
        }
        scheduleJobMapper.updateByPrimaryKeySelective(job);

    }

    /**
     * 添加任务 Quartz定时任务默认都是并发执行的，不会等待上一次任务执行完毕，只要间隔时间到就会执行,
     * 如果定时任执行太长，会长时间占用资源，导致其它任务堵塞。 当不使用spring的时候就需要在Job的实现类上加@DisallowConcurrentExecution的注释
     *
     * @param job
     * @throws SchedulerException
     * @DisallowConcurrentExecution 禁止并发执行多个相同定义的JobDetail, 这个注解是加在Job类上的,
     * 但意思并不是不能同时执行多个Job,
     * 而是不能并发执行同一个JobDefinition(由JobDetail定义),
     * 但是可以同时执行多个不同的JobDetail,
     * 举例说明,我们有一个Job类,叫做SayHelloJob,
     * 并在这个Job上加了这个注解, 然后在这个Job上定义了很多个JobDetail,
     * 如sayHelloToJoeJobDetail,
     * sayHelloToMikeJobDetail, 那么当scheduler启动时,
     * 不会并发执行多个sayHelloToJoeJobDetail或者sayHelloToMikeJobDetail
     * ,
     * 但可以同时执行sayHelloToJoeJobDetail跟sayHelloToMikeJobDetail
     */
    public void addJob(ScheduleJob job) throws SchedulerException {
        if (job == null
                || !ScheduleJob.STATUS_RUNNING.equals(job.getJobStatus())) {
            return;
        }

        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        log.debug(scheduler
                + ".......................................................................................add");
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(),
                job.getJobGroup());

        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

        // 不存在，创建一个
        if (null == trigger) {
            Class clazz = ScheduleJob.CONCURRENT_IS.equals(job
                    .getIsConcurrent()) ? QuartzJobFactory.class
                    : QuartzJobFactoryDisallowConcurrentExecution.class;

            JobDetail jobDetail = JobBuilder.newJob(clazz)
                    .withIdentity(job.getJobName(), job.getJobGroup()).build();

            jobDetail.getJobDataMap().put("scheduleJob", job);

            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                    .cronSchedule(job.getCronExpression());

            trigger = TriggerBuilder.newTrigger()
                    .withIdentity(job.getJobName(), job.getJobGroup())
                    .withSchedule(scheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            // Trigger已存在，那么更新相应的定时设置
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                    .cronSchedule(job.getCronExpression());

            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder).build();

            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    }

    /**
     * 从Java EE5规范开始，Servlet增加了两个影响Servlet生命周期的注解（Annotation）：
     *
     * @throws Exception
     * @PostConstruct和@PreConstruct。 这两个注解被用来修饰一个非静态的void()方法.而且这个方法不能有抛出异常声明。
     * 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行，
     * 并且只会被服务器调用一次，
     * 类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后，
     * init()方法之前运行。
     */
    @PostConstruct
    public void init() throws Exception {

        // Scheduler scheduler = schedulerFactoryBean.getScheduler();

        // 这里获取任务信息数据
        List<ScheduleJob> jobList = scheduleJobMapper.getAll();

        // 构造函数之后，初始化方法之前（服务器加载servlet的时候）获取所有的任务，添加到任务列表中，执行任务
        for(ScheduleJob job : jobList) {
            addJob(job);
        }
    }

    /**
     * 获取所有计划中的任务列表
     *
     * @return
     * @throws SchedulerException
     */
    public List<ScheduleJob> getAllJob() throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
        Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
        List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
        for(JobKey jobKey : jobKeys) {
            List<? extends Trigger> triggers = scheduler
                    .getTriggersOfJob(jobKey);
            for(Trigger trigger : triggers) {
                ScheduleJob job = new ScheduleJob();
                job.setJobName(jobKey.getName());
                job.setJobGroup(jobKey.getGroup());
                job.setDescription("触发器:" + trigger.getKey());
                Trigger.TriggerState triggerState = scheduler
                        .getTriggerState(trigger.getKey());
                job.setJobStatus(triggerState.name());
                if (trigger instanceof CronTrigger) {
                    CronTrigger cronTrigger = (CronTrigger) trigger;
                    String cronExpression = cronTrigger.getCronExpression();
                    job.setCronExpression(cronExpression);
                }
                jobList.add(job);
            }
        }
        return jobList;
    }

    /**
     * 所有正在运行的job
     *
     * @return
     * @throws SchedulerException
     */
    public List<ScheduleJob> getRunningJob() throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        List<JobExecutionContext> executingJobs = scheduler
                .getCurrentlyExecutingJobs();
        List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(
                executingJobs.size());
        for(JobExecutionContext executingJob : executingJobs) {
            ScheduleJob job = new ScheduleJob();
            JobDetail jobDetail = executingJob.getJobDetail();
            JobKey jobKey = jobDetail.getKey();
            Trigger trigger = executingJob.getTrigger();
            job.setJobName(jobKey.getName());
            job.setJobGroup(jobKey.getGroup());
            job.setDescription("触发器:" + trigger.getKey());
            Trigger.TriggerState triggerState = scheduler
                    .getTriggerState(trigger.getKey());
            job.setJobStatus(triggerState.name());
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                String cronExpression = cronTrigger.getCronExpression();
                job.setCronExpression(cronExpression);
            }
            jobList.add(job);
        }
        return jobList;
    }

    /**
     * 暂停一个job
     *
     * @param scheduleJob
     * @throws SchedulerException
     */
    public void pauseJob(ScheduleJob scheduleJob) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(),
                scheduleJob.getJobGroup());
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复一个job
     *
     * @param scheduleJob
     * @throws SchedulerException
     */
    public void resumeJob(ScheduleJob scheduleJob) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(),
                scheduleJob.getJobGroup());
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除一个job
     *
     * @param scheduleJob
     * @throws SchedulerException
     */
    public void deleteJob(ScheduleJob scheduleJob) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(),
                scheduleJob.getJobGroup());
        scheduler.deleteJob(jobKey);

    }

    /**
     * 立即执行job
     *
     * @param scheduleJob
     * @throws SchedulerException
     */
    public void runAJobNow(ScheduleJob scheduleJob) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(),
                scheduleJob.getJobGroup());
        scheduler.triggerJob(jobKey);
    }

    /**
     * 更新job时间表达式
     *
     * @param scheduleJob
     * @throws SchedulerException
     */
    public void updateJobCron(ScheduleJob scheduleJob)
            throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(),
                scheduleJob.getJobGroup());

        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        // 增加：withMisfireHandlingInstructionDoNothing()方法 
        // 1，不触发立即执行
        // 2，等待下次Cron触发频率到达时刻开始按照Cron频率依次执行
		/*CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
				.cronSchedule(scheduleJob.getCronExpression()).withMisfireHandlingInstructionDoNothing();*/
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                .cronSchedule(scheduleJob.getCronExpression());
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                .withSchedule(scheduleBuilder).build();

        scheduler.rescheduleJob(triggerKey, trigger);
    }

    /*
     * public static void main(String[] args) { CronScheduleBuilder
     * scheduleBuilder = CronScheduleBuilder.cronSchedule("xxxxx"); }
     */
}
